package com.king.juc.atomicdemo.aba;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicMarkableReference;

import static com.king.juc.utils.ThreadUtil.sleep;

/**
 * AtomicMarkableReference 案例
 *
 * @author king
 * @date 2020/12/1 13:11
 */
@Slf4j(topic = "c.AtomicMarkableReferenceDemo")
public class AtomicMarkableReferenceDemo {
    public static void main(String[] args) {
        GarbageBag bag = new GarbageBag("装满了垃圾");

        AtomicMarkableReference<GarbageBag> ref = new AtomicMarkableReference<>(bag, true);

        log.debug("start....");
        GarbageBag prev = ref.getReference();
        log.debug(prev.toString());

        new Thread(() -> {
            log.debug("start....");
            bag.setDesc("空垃圾袋");
            ref.compareAndSet(bag, bag, true, false);
            log.debug(bag.toString());
        }, "保洁阿姨").start();

        sleep(1);
        log.debug("想换一只新垃圾袋?");
        boolean success = ref.compareAndSet(prev, new GarbageBag("空垃圾袋"), true, false);
        log.debug("换了么? {}", success );
        log.debug(ref.getReference().toString());
    }
}
